package com.party.mobile.biz.crowdfund;

import com.alibaba.druid.support.json.JSONUtils;
import com.google.common.collect.Maps;
import com.party.common.constant.Constant;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.DateUtils;
import com.party.core.model.crowdfund.Support;
import com.party.core.model.crowdfund.SupportWithMember;
import com.party.core.model.crowdfund.TargetProject;
import com.party.core.model.distributor.*;
import com.party.core.service.crowdfund.IProjectReviseService;
import com.party.core.service.crowdfund.ISupportService;
import com.party.core.service.crowdfund.ITargetProjectService;
import com.party.core.service.distributor.IDistributorCountService;
import com.party.core.service.distributor.IDistributorDetailService;
import com.party.core.service.member.IMemberCopartnerCountService;
import com.party.core.service.member.IMemberCopartnerDetailService;
import com.party.mobile.biz.distributor.DistributorBizService;
import com.party.mobile.redisPubSub.publish.RedisMsgPublish;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;

/**
 * 众筹数据转换接口实现
 * Created by wei.li
 *
 * @date 2017/7/13 0013
 * @time 16:24
 */

@Service
public class SupportTransferBizService {

    @Autowired
    private ISupportService supportService;

    @Autowired
    private IProjectReviseService projectReviseService;

    @Autowired
    private ITargetProjectService targetProjectService;

    @Autowired
    private IMemberCopartnerCountService memberCopartnerCountService;

    @Autowired
    private IMemberCopartnerDetailService memberCopartnerDetailService;

    @Autowired
    private RedisMsgPublish redisMsgPublish;

    @Autowired
    private DistributorBizService distributorBizService;

    @Autowired
    private IDistributorDetailService distributorDetailService;

    @Autowired
    private IDistributorCountService distributorCountService;

    Logger logger = LoggerFactory.getLogger(getClass());


    public void transfer(String sourceId, String targetId, ExecutorService transferThreadPool){
        // 目标众筹
        DistributorRelation targetDisRelation = distributorBizService.getDistributorRelation(targetId);
        // 源众筹
        DistributorRelation sourceDisRelation = distributorBizService.getDistributorRelation(sourceId);

        List<SupportWithMember> list = supportService.findByProjectId(sourceId);
        for (SupportWithMember supportWithMember : list){

            transferThreadPool.execute(() -> supportTransfer(supportWithMember ,targetId));

            // 减去分销数据，删除分销详情
            subDisCount(sourceDisRelation, supportWithMember);

            // 增加分销数据，增加分销详情
            addDisCount(targetDisRelation, supportWithMember);
        }
        //转移完成后进行校验
        transferThreadPool.shutdown();
    }
    @Transactional
    public  void supportTransfer(SupportWithMember supportWithMember ,String targetId){
        Support support = supportWithMember;
        support.setProjectId(targetId);
        supportService.update(support);
    }

    public  void sendMessage(String message , String sessionId ){
        Map<String, String> json = Maps.newHashMap();
        json.put("message", message);
        json.put("sessionId", sessionId);
        String param = JSONUtils.toJSONString(json);
        redisMsgPublish.publish("projectTansferMobile", param);
    }

    public void reviseFavorer(String sourceId, String targetId) {
        //校正数据
        projectReviseService.reviseFavorer(sourceId);
        projectReviseService.reviseFavorer(targetId);

        //校正众筹目标数据
        TargetProject source = targetProjectService.findByProjectId(sourceId);
        TargetProject target = targetProjectService.findByProjectId(targetId);
        projectReviseService.reviseTarget(source.getTargetId());
        projectReviseService.reviseTarget(target.getTargetId());
    }

    /**
     * 减去分销数据，删除分销详情
     *
     * @param relation 分销关系
     * @param support  支持者数据
     */
    @Transactional
    public void subDisCount(DistributorRelation relation, SupportWithMember support) {
        if (null != relation) {
            try {
                distributorDetailService.deleteByTargetId(support.getOrderId(), relation.getId());

                DistributorCount distributorCount = distributorCountService.findByRelationIdLock(relation.getId());
                if (null != distributorCount) {
                    float sub = BigDecimalUtils.sub(distributorCount.getFavorerAmount(), support.getPayment());
                    sub = BigDecimalUtils.round(sub, 2);
                    distributorCount.setFavorerAmount(sub);
                    distributorCount.setFavorerNum(distributorCount.getFavorerNum() - 1);
                    distributorCount.setSalesNum(distributorCount.getSalesNum() - 1);
                    distributorCountService.update(distributorCount);

                    logger.info("减1111111；" + distributorCount.getFavorerAmount());
                }
            } catch (Exception e) {
                logger.error("减去分销数据，删除分销详情异常", e);
            }

            try {
                if (DistributorRelationType.CROWDFUND_DISTRIBUTION.getCode().equals(relation.getType())) {
                    memberCopartnerCountService.updateOrderAnalyzeSub(support.getPayment(), relation.getDistributorId());

                    String formatDate = DateUtils.formatDate(support.getCreateDate(), DateUtils.DATE_PATTERN);
                    String formatToday = DateUtils.formatDate(new Date(), DateUtils.DATE_PATTERN);
                    String option = formatToday.equals(formatDate) ? Constant.OPTION_ADD : Constant.OPTION_SUB;

                    memberCopartnerDetailService.updateOrderAnalyzeSub(support.getPayment(), relation.getDistributorId(), option);
                }
            } catch (Exception e) {
                logger.error("subDisCount合伙人统计异常", e);
            }
        }
    }

    /**
     * 增加分销数据，增加分销详情
     *
     * @param relation 分销关系
     * @param support  支持者数据
     */
    @Transactional
    public void addDisCount(DistributorRelation relation, SupportWithMember support) {
        if (null != relation) {
            try {
                DistributorDetail distributorDetail = distributorDetailService.get(support.getOrderId(),
                        DistributorDetailType.DISTRIBUTOR_TYPE_SUPPORT.getCode(), relation.getId());
                if (null == distributorDetail) {
                    distributorDetail = new DistributorDetail();
                    distributorDetail.setTargetId(support.getOrderId());
                    distributorDetail.setDistributorRelationId(relation.getId());
                    distributorDetail.setType(DistributorDetailType.DISTRIBUTOR_TYPE_SUPPORT.getCode());
                    distributorDetailService.insert(distributorDetail);

                    DistributorCount distributorCount = distributorCountService.findByRelationIdLock(relation.getId());

                    float add = BigDecimalUtils.add(distributorCount.getFavorerAmount(), support.getPayment());
                    add = BigDecimalUtils.round(add, 2);
                    distributorCount.setFavorerAmount(add);
                    distributorCount.setFavorerNum(distributorCount.getFavorerNum() + 1);
                    distributorCount.setSalesNum(distributorCount.getSalesNum() + 1);
                    distributorCountService.update(distributorCount);

                    logger.info("加22222222；" + distributorCount.getFavorerAmount());
                }
            } catch (Exception e) {
                logger.error("增加分销数据，增加分销详情异常", e);
            }

            try {
                if (DistributorRelationType.CROWDFUND_DISTRIBUTION.getCode().equals(relation.getType())) {
                    memberCopartnerCountService.updateOrderAnalyze(support.getPayment(), relation.getDistributorId());

                    memberCopartnerDetailService.updateOrderAnalyze(support.getPayment(), relation.getDistributorId());
                }
            } catch (Exception e) {
                logger.error("addDisCount合伙人统计异常", e);
            }
        }
    }
}
